<template>
  <div>
    <el-dialog title="分配权限" :visible.sync="visiable" width="500px" :before-close="handleClose" :close-on-click-modal="false">
      <el-button type="primary" plain size="mini"
                 @click="createParentNode()"
                 :disabled=" userRole !== 'SUPER_ADMIN' "
                 style="margin-bottom: 10px;">
        添加父节点
      </el-button>
      <el-form ref="formData" label-width="80px"  v-loading="loading">
        <!--
                :data 绑定的渲染数据，数组
                show-checkbox 显示勾选框
                node-key 树节点的唯一标识属性名
                props 配置响应数据中对应展示的属性名 children 是子菜单的属性名，label显示的菜单名属性名
                :default-checked-keys 默认勾选的集合
                accordion 每次只能展开一个，会将之前展开把它隐藏
        -->
        <el-tree ref="tree" :data="perList"
                 show-checkbox node-key="permissionId"
                 default-expand-all :expand-on-click-node="false"
                 :default-checked-keys="permissionIds"
                 :props="{children: 'children', label: 'permissionName'}">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>

            <span>
              <el-button  v-if="data.parentId === 0" type="text" size="mini"
                          @click="() => append(data)"
                          :disabled=" userRole !== 'SUPER_ADMIN' ">
                添加
              </el-button>
              <el-button  type="text" size="mini"
                          @click="() => edit(data)"
                          :disabled=" userRole !== 'SUPER_ADMIN' ">
                编辑
              </el-button>
              <el-button type="text" size="mini"
                         @click="() => remove(node, data)"
                         :disabled=" userRole !== 'SUPER_ADMIN' ">
                删除
              </el-button>
            </span>
          </span>
        </el-tree>
        <el-form-item align="center" style="margin-top: 20px;">
          <el-button type="primary"
                     @click="submitForm('formData')"
                     :disabled=" userRole !== 'SUPER_ADMIN' ">确定</el-button>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="400px">
      <el-form :model="permissionFormData" label-position="left">
        <el-form-item label="节点名称" label-width="120px" >
          <el-input v-model="permissionFormData.permissionName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="节点代码" label-width="120px">
          <el-input v-model="permissionFormData.permissionCode" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submit()" :disabled=" userRole !== 'SUPER_ADMIN' ">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTreePermissions,
  getPermissionByRoleId,
  saveRolePermissionRel,
  deletePermissionNode,
  createNode,
  getPermissionById,
  editNode,
  createParentNode } from "@/api/permission";
import { removeAllLoginInfo } from "@/utils/userToken";
import { getUserRole } from "@/utils/userToken";

let id = 1000;
export default {
  props:{
    visiable:{  // 弹出窗口
      type:Boolean,
      default:false
    },
    remoteClose: Function, // 用于关闭窗口
    roleId: {
      type: String,
      default:null
    },
    userRole: ''
  },

  data() {
    return {
      perList: [],       // 存储所有的菜单
      loading: false,     // 加载中  true 显示加载中
      permissionIds: [],        // 角色所拥有的的菜单ids
      dialogFormVisible: false,
      permissionFormData: {
        permissionCode: '',
        permissionName: ''
      },
      title: "新增权限",
      addOrEditParentId: '',
      invalid: true,
      currentRoleId: ''
    }
  },

  created() {
    this.fetchData();
    this.userRole = getUserRole();
  },

  watch:{
    roleId(val) {
      if(val) {
        this.getPermissionIdsByRoleId(val);
        this.fetchData();
      }
    }
  },

  methods: {
    // 根据角色ID查询该角色拥有的权限信息
    getPermissionIdsByRoleId(id) {
      getPermissionByRoleId(id).then(resp => {
        if (resp.code === 200) {
          this.permissionIds = resp.data;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    append(data) {
      this.addOrEditParentId = data.permissionId;
      this.title = "新增权限";
      this.dialogFormVisible = true;
    },

    createParentNode() {
      this.dialogFormVisible = true;
      this.title = "添加父节点";
      this.permissionFormData = {};
    },

    edit(data) {
      this.title = "编辑权限";
      this.addOrEditParentId = data.permissionId;
      this.dialogFormVisible = true;
      getPermissionById(data.permissionId).then(res => {
        if (res.code === 200) {
          this.permissionFormData = res.data
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    submit() {
      this.beforeSubmit();
      if (!this.invalid) {
        this.invalid = true;
        return;
      }
      if (this.title === '新增权限') {
        this.permissionFormData.parentId = this.addOrEditParentId
        createNode(this.permissionFormData).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '权限创建成功',
              type: 'success',
              duration: 1500
            });
            this.cancel();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
            this.invalid = true
          }
        })
      } else if (this.title === '编辑权限') {
        editNode(this.permissionFormData).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '权限编辑成功',
              type: 'success',
              duration: 1500
            });
            this.cancel();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
            this.invalid = true
          }
          this.title = "";
        })
      } else {
        createParentNode(this.permissionFormData).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '添加父节点成功',
              type: 'success',
              duration: 1500
            });
            this.cancel();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
            this.invalid = true
          }
          this.title = "";
        })
      }

    },

    cancel() {
      this.invalid = true;
      this.addOrEditParentId = '';
      this.permissionFormData = {}
      this.dialogFormVisible = false
      this.fetchData();
    },

    beforeSubmit() {
      if (!this.permissionFormData.permissionName) {
        this.$notify.error({
          title: '错误',
          message: "请输入权限名称",
          duration: 1500
        });
        this.invalid = false
        return
      }

      if (!this.permissionFormData.permissionCode) {
        this.$notify.error({
          title: '错误',
          message: "请输入权限代码",
          duration: 1500
        });
        this.invalid = false
      }
    },

    remove(node, data) {
      this.$confirm('确认删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const delData = {
          parentId: data.parentId,
          permissionId: data.permissionId
        }
        deletePermissionNode(delData).then(res => {
          if (res.code === 200) {
            this.fetchData();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
          }
        })
      }).catch(() => {
        // 取消删除
      });
    },

    // 关闭窗口
    handleClose(){
      this.perList = [];
      this.permissionIds = [];
      // 调用父组件的方法关闭窗口
      this.remoteClose();
    },

    fetchData() {
      getTreePermissions().then(response => {
        if (response.code === 200) {
          this.perList = response.data;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // 提交
    submitForm(formName) {
      const checkedPermissionIds = this.$refs.tree.getCheckedKeys();
      if (checkedPermissionIds.length === 0) {
        this.$notify.error({
          title: '错误',
          message: "请至少勾选一个权限",
          duration: 1500
        });
        return;
      }
      const data = {
        roleId: this.roleId,
        permissionIds: checkedPermissionIds
      }
      saveRolePermissionRel(data).then(res => {
        if (res.code === 200) {
          this.$confirm('权限分配成功，重新登录才能生效，是否重新登录?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 清除所有的登录信息
            removeAllLoginInfo();
            // 重新回到登录页面
            this.$router.push('/login');

          }).catch(() => {
            // 取消重新登录
            this.handleClose()
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },
  }
}
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
